package com.baiytfp.hf.HFDataExchange.action.controller.service;

import com.baiytfp.hf.baiytfp.common.db.DBManager;
import com.baiytfp.hf.baiytfp.framework.base.BaseController;
import com.baiytfp.hf.baiytfp.hfutils.HFDBHelper;
import com.baiytfp.hf.baiytfp.hfutils.HFRequest;
import com.baiytfp.hf.baiytfp.hfutils.HFResponse;
import com.baiytfp.hf.baiytfp.hfutils.HFWeb;
import com.baiytfp.hf.HFDataExchange.action.service.DeptService;
import com.baiytfp.hf.HFDataExchange.action.service.MenuService;
import com.baiytfp.hf.HFDataExchange.action.service.TreeService;
import com.baiytfp.hf.HFDataExchange.common.model.base.TableName;
import com.baiytfp.hf.HFDataExchange.common.model.state.TreeType;
import com.baiytfp.hf.HFDataExchange.common.model.table.Dept;
import com.baiytfp.hf.HFDataExchange.common.model.table.Menu;
import com.baiytfp.hf.HFDataExchange.common.model.table.Tree;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Controller
@RequestMapping("/service/dept")
public class DeptSController extends BaseController{

	@Autowired
	public DeptService deptService;

	@Autowired
	public TreeService treeService;

	public DeptSController() {

	}

	// Ajax 取得树( 只返回树数据，让前台自己组装 )(前台显示，有URL:href, 并且经过权限过滤)
	@RequestMapping(value="/treelistauth", method= RequestMethod.POST)
	public ModelAndView treelistauth(HttpServletRequest request,HttpServletResponse response) throws Exception {
		int treeType = TreeType.USER_DEPT.getKey();

		List<Map> list = null;

		String parentTreeCode = HFRequest.getIstance().getString(request,"parent_tree_code", "");

		//使用 feeService 进行读取信息，因为还需要读取附加属性
		list = deptService.getTree(treeType + "", false, HFWeb.getIstance().getUserCode(), parentTreeCode);

		HFResponse.getIstance().returnResult(response, list);

		return null;
	}



	// Ajax 取得树( 只返回树数据，让前台自己组装 )(前台显示，有URL:href, 并且经过权限过滤)
//	@RequestMapping("/getcategory")
//	public ModelAndView getcategory(HttpServletRequest request,HttpServletResponse response) throws Exception {
//
//		int treeType = TreeType.CATEGORY.getKey();
//
//		String parentSeqCode = RequestUtil.getString(request,"tree_seq_code", "");
//
//		StringBuffer sWhere = new StringBuffer();
//		List params = new ArrayList();
//		StringBuffer sql = new StringBuffer();
//		sql.append("select t1.*, attr.id as attr_id, attr.HAS_CHILD, attr.HAS_EDIT, attr.HAS_DEL, attr.HAS_MOVE, attr.item_desc from ");
//		sql.append(TableName.TREE + " t1 left join ");
//		sql.append(TableName.STD_CHKCATALOG + " attr on t1.seq=attr.tree_seq ");
//		sql.append(" where attr.expiry_time=? and TREE_TYPE=? and seq_code like ? and (IS_OPEN=1 OR IS_OPEN IS NULL) ");
//		sql.append(" order by node_deep asc, parent_seq_code, node_order asc ");
//
//		List<Map> list = commonService.getItemMapList(DBManager.getConnection(),sql.toString(), new Object[]{TableVersionHelper.getVersionEndTime(),treeType,parentSeqCode+"%"});
//
//		HFResponse.getIstance().returnResult(response, list);
//
//		return null;
//	}

	/*****************************下面方法为结点的增删改操作******************************************/

	// 添加一个类型结点
	@RequestMapping(value="/tnodeadd", method= RequestMethod.POST)
	public ModelAndView tnodeadd(HttpServletRequest request,HttpServletResponse response) throws Exception {

		int treeType = TreeType.USER_DEPT.getKey();

		String parentTreeCode = HFRequest.getIstance().getString(request,"parent_tree_code", "-1");


		Tree treeVO = HFWeb.getIstance().toBean(request, Tree.class);

		treeVO.setTree_type(treeType);

		treeVO.setId(HFDBHelper.getIDGenerator());

		treeVO.setChildren_number(0);	//新结点，没有子结点

		String newSeqCode = treeService.getNewSeqCode(treeVO.getParent_tree_code(), treeType + ""); // 取得新流水号
		treeVO.setNode_order(treeService.setChildNodeOrder(treeVO.getParent_tree_code(), 0, "000", treeType + ""));  // 对新父结点的孩子（非此结点）进行序号排序
		treeVO.setTree_code(newSeqCode);

		//设置个性附加属性内容
		Dept deptVO = HFWeb.getIstance().toBean(request, Dept.class);
		deptVO.setTree_id(treeVO.getId());

		//设置树结点名
		treeVO.setNode_name(deptVO.getDept_name());


		Connection connection = null;
		try {
			connection = DBManager.getConnection(); // 获取连接池
			DBManager.beginTransaction(connection); // 打开事务

			//先添加树结点
			HFDBHelper.add(connection, TableName.TREE, treeVO);
			//添加附加属性
			HFDBHelper.add(connection, TableName.DEPT, deptVO);

			if(!"-1".equals(parentTreeCode)){	// 父结点孩子数加 一
				Tree parentTree = HFDBHelper.read(connection, TableName.TREE, " where TREE_TYPE = ? and TREE_CODE=?  ", Tree.class, new Object[]{ treeType + "", treeVO.getParent_tree_code()});

				parentTree.setChildren_number(parentTree.getChildren_number() + 1);

				HFDBHelper.update(connection, TableName.TREE, " where id=? ", parentTree, parentTree.getId() );
			}

			DBManager.commitTransaction(connection); // 提交事务
		} catch (SQLException se) {
			DBManager.rollbackTransaction(connection); // 回滚事务
			throw se;
		} finally {
			DBManager.close(connection); // 涉及事务且外面传进来的连接不在这里关闭
		}

		Map resultMap = new HashMap();
		resultMap.put("treeVO", treeVO);
		resultMap.put("deptVO", deptVO);

		HFResponse.getIstance().returnResult(response, resultMap);

		return null;
	}

	//编辑结点
	@RequestMapping(value="/tnodeedit", method= RequestMethod.POST)
	public ModelAndView tnodeedit(HttpServletRequest request,HttpServletResponse response) throws Exception {

		int treeType = TreeType.USER_DEPT.getKey();


		String treeCode = HFRequest.getIstance().getString(request,"tree_code", "");

		Tree treeVO = treeService.getNodeInfo(treeCode, treeType + "");

		treeVO = HFWeb.getIstance().toBean(request, treeVO);

		Dept deptVO = null;

		Connection connection = null;
		try {
			connection = DBManager.getConnection(); // 获取连接池
			DBManager.beginTransaction(connection); // 打开事务

			deptVO = HFDBHelper.read(connection, TableName.DEPT, " t where exists (select id from " + TableName.TREE + " where id=t.tree_id and tree_code = ? ) ", Dept.class, treeCode);

			//先更新菜单
			if(deptVO == null){	//为空时则新增一个
				deptVO = HFWeb.getIstance().toBean(request, Dept.class);
				deptVO.setTree_id(treeVO.getId());
				HFDBHelper.add(connection, TableName.DEPT, deptVO);

			}else{
				deptVO = HFWeb.getIstance().toBean(request, deptVO);

				HFDBHelper.update(connection, TableName.DEPT, " where tree_id=? ", deptVO, deptVO.getTree_id());
			}


			//设置树结点名
			treeVO.setNode_name(deptVO.getDept_name());

			//再更新树结点
			HFDBHelper.update(connection, TableName.TREE, " where id=? ", treeVO, treeVO.getId());

			DBManager.commitTransaction(connection); // 提交事务
		} catch (SQLException se) {
			DBManager.rollbackTransaction(connection); // 回滚事务
			throw se;
		} finally {
			DBManager.close(connection); // 涉及事务且外面传进来的连接不在这里关闭
		}

		Map resultMap = new HashMap();
		resultMap.put("treeVO", treeVO);
		resultMap.put("deptVO", deptVO);

		HFResponse.getIstance().returnResult(response, resultMap);

		return null;

	}

	// 移动一个类型结点
	@RequestMapping(value="/tnodemove", method= RequestMethod.POST)
	public ModelAndView tnodemove(HttpServletRequest request,HttpServletResponse response) throws Exception {

		int treeType = TreeType.USER_DEPT.getKey();

//		String seq = RequestUtil.getString(request,"seq", "");
		String treeCode = HFRequest.getIstance().getString(request,"treeCode", "");
		int nodeOrder = HFRequest.getIstance().getInt(request,"nodeOrder", 0);

		Tree treeVO = treeService.getNodeInfo(treeCode, treeType + "");
		treeVO.setNode_order(nodeOrder);

		// 更新“新”父结点的排序，留出空排序号给此结点
		// 当父结点相同时，$arr_deptVO['SEQ_CODE']才会起作用，也就是不对这个结点排序，等下面直接更新
		treeService.setChildNodeOrder(treeVO.getParent_tree_code(), nodeOrder, treeVO.getTree_code(), treeType + "");

		long res = HFDBHelper.update( TableName.TREE, " where id=? ", treeVO, treeVO.getId());

		HFResponse.getIstance().returnResultByRes(response, res);

		return null;
	}

	@RequestMapping(value="/tnodemove2", method= RequestMethod.POST)
	public ModelAndView tnodemove2(HttpServletRequest request,HttpServletResponse response) throws Exception {

		String treeType = TreeType.USER_DEPT.getKey() + "";

//		String seq = RequestUtil.getString(request,"seq", "");
		String treeCode = HFRequest.getIstance().getString(request,"treeCode", "");
		String parentTreeCode = HFRequest.getIstance().getString(request,"parentTreeCode", "");
		int nodeDeep = HFRequest.getIstance().getInt(request,"nodeDeep", 0);
		int nodeOrder = HFRequest.getIstance().getInt(request,"nodeOrder", 0);

		Tree treeVO = treeService.getNodeInfo(treeCode, treeType);

		// 取得深度的变化值
		int deepDiff = 0;
		deepDiff = nodeDeep - treeVO.getNode_deep();

		String oldParentTreeCode = treeVO.getParent_tree_code();
		int oldNodeOrder = treeVO.getNode_order();

		// 如果父结点不为空，则更新
		if(!"".equals(parentTreeCode)){
			treeVO.setParent_tree_code(parentTreeCode);
		}

		// 更新深度
		if(nodeDeep != 0){
			treeVO.setNode_deep(nodeDeep);
		}
		// 更新排序号
		if(nodeOrder != 0){
			treeVO.setNode_order(nodeOrder);
		}


		// 判断父结点是否改变
		if(!oldParentTreeCode.equals(parentTreeCode)){
			String newSeqCode = treeService.getNewSeqCode(parentTreeCode, treeType); // 取得新流水号
			treeVO.setTree_code(newSeqCode);

			// 更新“新”父结点的孩子总数
			if(!"-1".equals(parentTreeCode)){
				Tree parentTree = HFDBHelper.read(TableName.TREE, " where TREE_TYPE = ? and TREE_CODE=?  ", Tree.class, new Object[]{ treeType + "", parentTreeCode});

				parentTree.setChildren_number(parentTree.getChildren_number() + 1);

				HFDBHelper.update(TableName.TREE, " where id=? ", parentTree, parentTree.getId() );
			}
			// 更新“旧”父结点的孩子总数
			if(!"-1".equals(oldParentTreeCode)){
				Tree oldParentTree = HFDBHelper.read(TableName.TREE, " where TREE_TYPE = ? and TREE_CODE=?  ", Tree.class, new Object[]{ treeType + "", oldParentTreeCode});

				oldParentTree.setChildren_number(oldParentTree.getChildren_number() - 1);

				HFDBHelper.update(TableName.TREE, " where id=? ", oldParentTree, oldParentTree.getId() );

			}
		}


//		String seq = RequestUtil.getString(request,"seq", "");
//		String seqCode = RequestUtil.getString(request,"seqCode", "");
//		int nodeOrder = RequestUtil.getInt(request,"nodeOrder", 0);
//
//		Tree treeVO = treeService.getNodeInfo(seqCode, treeType + "");
//		treeVO.setNode_order(nodeOrder);

		// 更新“新”父结点的排序，留出空排序号给此结点
		// 当父结点相同时，$arr_deptVO['SEQ_CODE']才会起作用，也就是不对这个结点排序，等下面直接更新
//		treeService.setChildNodeOrder(treeVO.getParent_seq_code(), nodeOrder, treeVO.getSeq_code(), treeType + "");
		treeService.setChildNodeOrder(parentTreeCode, nodeOrder, treeVO.getTree_code(), treeType);

		long res = HFDBHelper.update(TableName.TREE, " where id=? ", treeVO, treeVO.getId() );


//		Dept deptVO = HFDBHelper.read(TableName.DEPT, " where TREE_CODE=?  ", Dept.class, treeCode);
//		deptVO.setTree_code(treeVO.getTree_code());
//		HFDBHelper.update(TableName.DEPT, " where TREE_CODE=? ", deptVO, treeCode );


		// 判断父结点是否改变
		if(!oldParentTreeCode.equals(parentTreeCode)){
			// 更新子结点信息（子结点的父结点改变）
			treeService.updateChildrenSeqCode(treeVO.getTree_code(), treeCode, deepDiff, treeType);

			// 更新“旧”父结点的排序
			// 当父结点相同时，下面的语句无意义; 只有当父结点改变了，才会更新一下旧父结点的排序
			treeService.setChildNodeOrder(oldParentTreeCode, 0, "000", treeType);

			List list = treeService.getNodeListByParent(treeVO.getTree_code(), treeType);
		}



		HFResponse.getIstance().returnSuccess(response);

		return null;
	}

	// 删除一个菜单结点
	@RequestMapping(value="/tnodedel", method= RequestMethod.POST)
	public ModelAndView tnodedel(HttpServletRequest request,HttpServletResponse response) throws Exception {

		int treeType = TreeType.USER_DEPT.getKey();

//		String seq = RequestUtil.getString(request,"seq", "");
		String treeCode = HFRequest.getIstance().getString(request,"treeCode", "");
		String parentTreeCode = HFRequest.getIstance().getString(request,"parentTreeCode", "-1");
		
		Tree treeVO = treeService.getNodeInfo(treeCode, treeType+"");
		
		if(treeVO.getChildren_number()>0){
			HFResponse.getIstance().returnResult(response, -1, "该部门下还有子部门，请先移除子部门！", "");
			return null;
		}else if(deptService.isHasStaff(treeVO)){
			HFResponse.getIstance().returnResult(response, -1, "该部门下还有员工，请先移除员工！", "");
			return null;
		}else if(deptService.isInit(treeCode)){
			HFResponse.getIstance().returnResult(response, -1, "初始化数据，请勿删除！", "");
			return null;
		}else{
			deptService.tnodedel(treeVO);

			HFResponse.getIstance().returnSuccess(response);
		}
		return null;
	}
	
	
	// 删除一个菜单结点
	/*@RequestMapping(value="/tnodedel", method= RequestMethod.POST)
	public ModelAndView tnodedel(HttpServletRequest request,HttpServletResponse response) throws Exception {
		
		int treeType = TreeType.USER_DEPT.getKey();
		
		String treeCode = HFRequest.getIstance().getString(request,"treeCode", "");
		String parentTreeCode = HFRequest.getIstance().getString(request,"parentTreeCode", "-1");
		
		Connection connection = null;
		try {
			connection = DBManager.getConnection(); // 获取连接池
			DBManager.beginTransaction(connection); // 打开事务

			HFDBHelper.delete(connection, TableName.DEPT, " where exists (select id from " + TableName.TREE + " where id=tree_id and tree_code like ? ) ", treeCode + "%");

			HFDBHelper.delete(connection, TableName.TREE, " where TREE_TYPE = ? and TREE_CODE like ?  ", new Object[]{treeType + "",treeCode + "%" });

			if(!"-1".equals(parentTreeCode)){
				Tree parentTree = HFDBHelper.read(connection, TableName.TREE, " where TREE_TYPE = ? and TREE_CODE=?  ", Tree.class, new Object[]{ treeType + "", parentTreeCode});

				parentTree.setChildren_number(parentTree.getChildren_number() - 1);

				HFDBHelper.update(connection, TableName.TREE, " where id=? ", parentTree, parentTree.getId() );
			}

			DBManager.commitTransaction(connection); // 提交事务
		} catch (SQLException se) {
			DBManager.rollbackTransaction(connection); // 回滚事务
			throw se;
		} finally {
			DBManager.close(connection); // 涉及事务且外面传进来的连接不在这里关闭
		}

		HFResponse.getIstance().returnSuccess(response);
		
	}*/


}
